package com.astrocsr.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;

import com.astrocsr.business.AuditLogManager;
import com.astrocsr.common.Constants;
import com.astrocsr.common.helper.ContextHelper;

public class LogoutHandler extends
	SimpleUrlLogoutSuccessHandler {

	@Autowired
	private AuditLogManager auditLogManager; 
	
	public LogoutHandler() {
	}

	public void onLogoutSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication) {
		try {
			if (authentication != null ) {
				System.out.println("Catch Logout Successfully : " + authentication.getName());
				// get Group Code
				String groupCode = "";
				try {
					Object obj = authentication.getPrincipal();
			        if (obj != null && obj instanceof WebUserDetails) {
			        	WebUserDetails webUD = (WebUserDetails) obj;
			        	groupCode = webUD.getAuthorities().get(0).getAuthority();
			        }
				} catch (Exception ae) {}

				// insert log
				auditLogManager.addAuditlog(
						Constants.LOG_ACCT_TYPE_ACCESS,	//0
						Constants.LOG_AcccessCode_Logout, 	//1 
						Constants.LOG_AcccessName_Logout, 	//2
						authentication.getName(), 		//3
						groupCode, 	//4
						"Logout", //5
						request.getRemoteAddr()				//6
						);
			} else {
				System.out.println("User already logouted : ");
			}

			super.onLogoutSuccess(request, response, authentication);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
	}
}
